package cn.pa4j.service;

import cn.hutool.json.JSONObject;
import cn.pa4j.entity.Live;
import cn.pa4j.mapper.H2Mapper;
import cn.pa4j.utils.LiveUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LiveNotificationService {
    @Autowired
    H2Mapper mapper;

    public List<Live> getLotinfo(String id) {
        mapper.creatLive();
        return mapper.getLivesByRoomId(id);
    }

    public String getLives(String userid) {
        List<Live> lives = mapper.getLivesByUserId(userid);
        if (lives.size()==0){
            return "暂未订阅任何直播间！";
        }else {
            StringBuilder result = new StringBuilder();
            result.append("已订阅以下直播间：\n");
            for (Live live : lives) {
                result.append(live.getRoomid());
                JSONObject object = LiveUtil.check(live.getRoomid());
                if ("1".equals(object.getStr("live_status"))){
                    result.append("正在直播：");
                    result.append(object.getStr("title"));
                }else {
                    result.append("未开播。");
                }
                result.append("\n");
            }
            return result.toString();
        }
    }

    public String subscribe(String userId, String roomId) {
        List<Live> liveList = mapper.getLivesByUserIdAndRoomId(userId, roomId);
        if (liveList.size()>0){
            return "已订阅过直播间："+roomId;
        }else {
            mapper.addLive(new Live(userId,roomId));
            JSONObject object = LiveUtil.check(roomId);
            StringBuilder result = new StringBuilder();
            result.append("订阅成功\n");
            if ("1".equals(object.getStr("live_status"))){
                result.append("该直播间正在直播：");
                result.append(object.getStr("title"));
            }else {
                result.append("该直播间未开播。");
            }
            return result.toString();
        }
    }

    public String unsubscribe(String userId, String roomId) {
        List<Live> liveList = mapper.getLivesByUserIdAndRoomId(userId, roomId);
        if (liveList.size()==0){
            return "尚未订阅直播间："+roomId;
        }else {
            mapper.cancleLive(userId,roomId);
            return "取消订阅成功";
        }
    }
}
